package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import utile.Md5;
import model.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author lk
 * @create 2022-12-13 11:17
 */
@WebServlet("/register")
public class UserRegisterServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置字符格式
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        //以字符流的形式接收数据
        BufferedReader reader = new BufferedReader(req.getReader());
        StringBuilder json = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }
        //将接收到的数据转换成一个User对象
        User user = JSON.parseObject(json.toString(), User.class);

        //创建一个用来传数据的JSON对象
        JSONObject message = new JSONObject();
        //判断用户名是否已经存在
        if (userService.findByName(user.getUsername()) != -1) {
            //状态0表示出错，1代表正确
            message.put("status", "0");
            message.put("Msg", "用户名已存在");
            resp.getWriter().write(message.toString());
            return;
        }
        //判断邮箱是否已经存在
        if (userService.findByEmile(user.getEmail()) != -1) {
            message.put("status", "0");
            message.put("Msg", "邮箱已存在");
            resp.getWriter().write(message.toString());
            return;
        }
        //判断手机号是否已经存在
        if (userService.findByPhone(user.getPhone()) != -1) {
            message.put("status", "0");
            message.put("Msg", "手机号已存在");
            resp.getWriter().write(message.toString());
            return;
        }

        //md5加密
        Md5 md5 = new Md5();
        String password = md5.encryption(user.getPassword());
        user.setPassword(password);

        //数据库添加失败
        if (!userService.insert(user)) {
            message.put("status", "0");
            message.put("Msg", "注册失败");
            resp.getWriter().write(message.toString());
            return;
        }

        //向前端发送正确的状态已经要跳转的页面
        message.put("status", "1");
        resp.getWriter().write(message.toString());
    }
}
